const { Service } = require("egg");

class UserService extends Service {
    /**
     * 根据用户名，查询用户信息
     * @param {string} username 用户名
     */
    async findByUsername(username) {
        let sql = "select * from user where username = ?";
        let params = [username];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 添加用户信息
     * @param {string} username 用户名
     * @param {string} password 用户密码
     * @param {string} nickname 用户昵称
     */
    async addUser(username, password, nickname = "") {
        let sql =
            "insert into user (username, password, nickname) values (?, ?, ?)";
        let params = [username, password, nickname];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 根据用户id，修改用户密码
     * @param {string} password 要修改的新密码
     * @param {number} id 用户id
     */
    async updatePassword(password, id) {
        let sql = "update user set password = ? where id = ?";
        let params = [password, id];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 删除用户
     */
    async remove(id) {
        let sql = "delete from user where id = ?";
        let params = [id];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 修改用户信息
     * @param {string} nickname 用户昵称
     */
    async update(nickname) {
        let sql = "update user set nickname = ? where id = ?";
        let params = [nickname, this.ctx.user.id];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }
}

module.exports = UserService;
